package com.geek.novel.services

import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import android.widget.ImageView
import com.geek.novel.R
import com.geek.novel.activity.base.BaseActivity
import com.geek.novel.common.Constant
import com.geek.novel.network.RslHandler
import com.geek.novel.utils.*
import com.geek.novel.vo.ApiErrorResult
import com.geek.novel.vo.ApiResult
import com.yalantis.ucrop.UCrop
import com.yalantis.ucrop.callback.BitmapLoadCallback
import com.yalantis.ucrop.model.AspectRatio
import com.yalantis.ucrop.model.ExifInfo
import com.yalantis.ucrop.util.BitmapLoadUtils
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream

/**
 * 图片服务类
 */
class ImageService(val context: BaseActivity): RslHandler {

    private var fileService: FileService? = null

    /** ImageView对象  */
    private val items = arrayOf("选择本地图片", "拍照")

    /** 请求码  */
    private val IMAGE_REQUEST_CODE = 0
    private val CAMERA_REQUEST_CODE = 1
    private val RESULT_REQUEST_CODE = 2

    /** 头像名称  */
    private val IMAGE_FILE_NAME = "image.jpg"

    fun getFileService(): FileService{
        if(fileService == null){
            fileService = FileService(this)
        }
        return fileService!!
    }

    /**用户拍照的头像，后面会删除*/
    private var takePhotoImageFile: File? = null
    //选择头像
    fun showChooseImageDialog(){
        AlertDialog.Builder(context)
            .setTitle("设置头像")
            .setItems(items) { _, which ->
                when (which) {
                    0 -> {
						val intent = Intent(Intent.ACTION_GET_CONTENT)
								.setType("image/*")
								.addCategory(Intent.CATEGORY_OPENABLE)
						val mimeTypes = arrayOf("image/*")
						intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
						context.startActivityForResult(intent, IMAGE_REQUEST_CODE)
                    }
                    1 -> {
                        val intentFromCapture = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                        // 判断存储卡是否可以用，可用进行存储
                        val state = Environment.getExternalStorageState()
                        if (state == Environment.MEDIA_MOUNTED) {
                            val path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
                            takePhotoImageFile = File(path, IMAGE_FILE_NAME)

                            if(!takePhotoImageFile!!.exists()){
                                takePhotoImageFile!!.createNewFile()
                            }
                            val uri = FileUtil.getFileUri(context, intentFromCapture, takePhotoImageFile!!)
                            intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, uri)
                        }
                        context.startActivityForResult(intentFromCapture, CAMERA_REQUEST_CODE)
                    }
                }
            }
            .setNegativeButton("取消") { _, _ ->
            }.show()

    }


    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode != Activity.RESULT_CANCELED) {
            when (requestCode) {
                IMAGE_REQUEST_CODE -> if (data != null) {
                    val uri = data.data!!
//                    val picturePath = handleImageOnKitKat(uri!!)
//                    startPhotoZoom(picturePath)
					startCrop(uri)
                }
                CAMERA_REQUEST_CODE -> {
                    // 判断存储卡是否可以用，可用进行存储
                    val state = Environment.getExternalStorageState()
                    if (state == Environment.MEDIA_MOUNTED) {
                        val path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
                        val tempFile = File(path, IMAGE_FILE_NAME)
//                        startPhotoZoom(tempFile.absolutePath)
						val uri = Uri.fromFile(tempFile)
						startCrop(uri)
                    } else {
                        ToastUtils.toast("未找到存储卡，无法存储照片！")
                    }
                }
//                // 图片缩放完成后
//                RESULT_REQUEST_CODE -> if (data != null) {
//                    getImageToView(data)
//                }
				//改用第三方工具的缩放了，上面的已经废了
				UCrop.REQUEST_CROP ->{
					getImageToView(data)
				}
            }
        }
    }
	
	private fun startCrop(uri: Uri) {
		val destinationFileName = "${Constant.CROPPED_IMAGE_NAME}.png"
		val options = UCrop.Options()
		options.setCompressionFormat(Bitmap.CompressFormat.PNG)
		options.setCircleDimmedLayer(true)//设置椭圆形
		options.setCompressionQuality(80)//设置图片质量0到100
		//设置图像大小
		options.setAspectRatioOptions(
				0,
				AspectRatio("1 : 1", 1F, 1F),
//			AspectRatio("WOW", 1F, 2F),
//			AspectRatio("MUCH", 3F, 4F),
//			AspectRatio("RATIO", CropImageView.DEFAULT_ASPECT_RATIO, CropImageView.DEFAULT_ASPECT_RATIO),
//			AspectRatio("SO", 16F, 9F),
		)
		
		val uCrop = UCrop.of(uri, Uri.fromFile(File(context.cacheDir, destinationFileName))).withOptions(options)
		
		uCrop.start(context)
	}
	

//    /**处理图片路径*/
//    private fun handleImageOnKitKat(uri: Uri): String? {
//        var imagePath: String? = null
//        if (DocumentsContract.isDocumentUri(context, uri)) {
//            val docId = DocumentsContract.getDocumentId(uri) ?: return imagePath
//            if ("com.android.providers.media.documents" == uri.authority) {
//                val id = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[1]
//                val selection = MediaStore.Images.Media._ID + "=" + id
//                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection)
//            } else if ("com.android.providers.downloads.documents" == uri.authority) {
//                val contentUri = ContentUris.withAppendedId(
//                    Uri.parse("content://downloads/public_downloads"),
//                    java.lang.Long.valueOf(docId)
//                )
//                imagePath = getImagePath(contentUri, null)
//            }
//        } else if ("content".equals(uri.scheme, ignoreCase = true)) {
//            imagePath = getImagePath(uri, null)
//        }
//        return imagePath
//    }
//
//
//    /**获取图片路径*/
//    private fun getImagePath(uri: Uri, selection: String?): String? {
//        var path: String? = null
//        val cursor = context.contentResolver.query(uri, null, selection, null, null)
//        if (cursor != null) {
//            if (cursor.moveToFirst()) {
//                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))
//            }
//            cursor.close()
//        }
//        return path
//    }


//    /**
//     * 裁剪图片方法实现
//     */
//    private fun startPhotoZoom(url:String?) {
//        if(url == null){
//            ToastUtils.toast("图片获取失败！")
//            return
//        }
//        val intent = Intent("com.android.camera.action.CROP")
//
//        val fileUri = FileUtil.getFileUri(context, intent, File(url))
//        intent.setDataAndType(fileUri, "image/*")
//        intent.putExtra("output", fileUri)
//        // 设置裁剪
//        intent.putExtra("crop", "true")
//        // aspectX aspectY 是宽高的比例
//        intent.putExtra("aspectX", 1)
//        intent.putExtra("aspectY", 1)
//        // outputX outputY 是裁剪图片宽高
//        intent.putExtra("outputX", 340)
//        intent.putExtra("outputY", 340)
//        intent.putExtra("return-data", true)
//        context.startActivityForResult(intent, RESULT_REQUEST_CODE)
//    }

    /**
     * 保存裁剪之后的图片数据
     */
    private fun getImageToView(data: Intent?) {
		if(data == null){
			ToastUtils.toast("获取裁剪结果失败！")
			return
		}
        //存在之前拍照的图片，删掉
        if(takePhotoImageFile != null){
            takePhotoImageFile!!.delete()
            takePhotoImageFile = null
        }
        //获取裁剪之后的图片
//        val extras = data.extras
//        if (extras != null) {
//            val photo = extras.getParcelable<Bitmap>("data")
//            context.sendHandlerMessage(Constant.handler_event_selected_image, photo)
//        }
		val resultUri = UCrop.getOutput(data)
		if (resultUri != null) {
			//显示裁剪后的图片
			try {
				val maxBitmapSize = BitmapLoadUtils.calculateMaxBitmapSize(context)
				
				BitmapLoadUtils.decodeBitmapInBackground(context, resultUri, null, maxBitmapSize, maxBitmapSize,
					object : BitmapLoadCallback {
						override fun onBitmapLoaded(bitmap: Bitmap, exifInfo: ExifInfo, imageInputUri: Uri, imageOutputUri: Uri?) {
							context.sendHandlerMessage(Constant.handler_event_selected_image, bitmap)
						}
						override fun onFailure(bitmapWorkerException: java.lang.Exception) {
						}
					})
			} catch (e: Exception) {
				LogCatUtil.e("???", e.message!!, e)
				ToastUtils.toast(e.message!!)
			}
		} else {
			ToastUtils.toast("图片裁剪失败！返回uri为空！")
		}
		
    }

    /**保存图片到存储卡*/
    fun saveBitmap(bitmap: Bitmap, fileName: String): File? {
        val file: File?
        val pathFile = this.createImagePathFile() ?: return null
        file = File(pathFile, fileName)
        if (file.exists()) {
            file.delete()
        }
        val out: FileOutputStream
        try {
            out = FileOutputStream(file)
            if (bitmap.compress(Bitmap.CompressFormat.PNG, 90, out)) {
                out.flush()
                out.close()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            ToastUtils.toast(e.message)
        }
        return file
    }


    /**获取本地图片的保存路径，如果不存在，则创建文件夹*/
    private fun createImagePathFile(): File?{
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            val pathString = Constant.ImagesPath
            val pathFile = File(pathString)
            if (!pathFile.exists()) {
                pathFile.mkdirs()
            }
            return pathFile
        }else{
            ToastUtils.toast("您的存储卡状态异常,暂时无法更换头像!")
        }
        return null
    }

    /**传进来的用户头像的ImageView*/
    var ivUserInfoHeader: ImageView? = null
    /**获取用户头像*/
    fun parseUserImage(iv: ImageView){
        ivUserInfoHeader = iv
        val user = SecurityUtil.getPrincipal()
        if(user?.imageId == null || user.imageId == 0L){
            iv.setImageResource(R.drawable.img_default_header)
            //显示默认头像
            return
        }
        // 判断本地是否存在图片文件
        val parentFile = this.createImagePathFile() ?: return
        val fileName = CommUtil.getUserHeaderImageName()
        val file = File(parentFile, fileName)
        if(file.exists()){
            //读取本地图片
            val fis = FileInputStream(file)
            val bitmap = BitmapFactory.decodeStream(fis)
            iv.setImageBitmap(bitmap)
            return
        }
        //请求服务器下载图片文件
        getFileService().downloadImage(user.imageId!!, Constant.HTTP_KEY_DOWNLOAD_USER_IMAGE)
    }

    override fun onError(code: Int, err: ApiErrorResult) {
    }

    override fun onSuccess(result: ApiResult, code: Int) {
        when(code){
            //上传文件
            Constant.HTTP_KEY_UPLOAD_FILE->{
                context.sendHandlerMessage(Constant.handler_event_upload_file_finish, result.getData())
            }
            //下载文件
            Constant.HTTP_KEY_DOWNLOAD_FILE->{
                if(ivUserInfoHeader != null){
                    val imageBitmap = result.getData() as Bitmap
                    //保存文件到本地
                    val fileName = CommUtil.getUserHeaderImageName() ?: throw RuntimeException("保存的头像文件名不能为空！")
                    this.saveBitmap(imageBitmap, fileName)
                }
            }
            //下载用户头像
            Constant.HTTP_KEY_DOWNLOAD_USER_IMAGE->{
                if(ivUserInfoHeader != null){
                    //设置用户头像
                    val imageBitmap = result.getData() as Bitmap
                    ivUserInfoHeader!!.setImageBitmap(imageBitmap)
                    //保存文件到本地
                    val fileName = CommUtil.getUserHeaderImageName() ?: throw RuntimeException("保存的头像文件名不能为空！")
                    this.saveBitmap(imageBitmap, fileName)
                }
            }
        }
    }

	companion object{
		/**删除用户本地图片*/
		fun deleteUserImage(){
			// 判断本地是否存在图片文件
			val pathString = Constant.ImagesPath
			val fileName = CommUtil.getUserHeaderImageName()
			if(!TextUtils.isEmpty(fileName)){
				val parentFile = File(pathString)
				val file = File(parentFile, fileName)
				if(file.exists()){
					file.delete()
				}
			}
		}
	}

}